<?php
namespace app\admin\model;
use \think\session;
use \think\Model;
class Article extends Model
{
    /**
     * 查询
     */
	public function sel($art_title = "")
    {
        $where['a.is_del'] = 0;
        if (!empty($art_title)) {
            $where['a.art_title'] = ["like","%$art_title%"];
        }
        $list = $this->alias("a")
            ->field("a.article_id,a.art_title,a.keyword,a.describe,a.art_content,
            a.label,a.cate_id,a.state,a.is_del,a.last_time,a.release_time,a.author_id,
            a.forbid_comment,a.top,c.cate_name,m.username as author_user")
            ->join("__CATE__ c","a.cate_id = c.cate_id","left")
            ->join("__MANAGE__ m","a.author_id = m.manage_id","left")
            ->order("a.article_id desc")
            ->where($where)
            ->paginate(15)
            ->each(function($item, $key){
                if ($item->last_time == 0) {
                    $item->last_time = '--';
                } else {
                    $item->last_time = date("Y-m-d H:i",$item->last_time);
                }
                if ($item->release_time == 0) {
                    $item->release_time = '--';
                } else {
                    $item->release_time = date("Y-m-d H:i",$item->release_time);
                }
            });
        return $list;
    }

    /**
     * 删除
     */
    public function del($article_id)
    {
        if ($article_id > 0) {
            $result = $this->save(['is_del' => 1],['article_id' => $article_id]);
            return $result;
        }
    }

    /**
     * 新增
     */
    public function add($data)
    {
        if ($data['state'] == 1) {
            $data['release_time'] = time();
        } else {
            $data['release_time'] = 0;
        }
        $data['last_time'] = time();
        $data['author_id'] = Session::get("admin")["manage_id"];
        $this->data($data);
        $result = $this->save();
        return $result;
    }

    /**
     * 查询文章信息
     */
    public function findArt($article_id)
    {
        $manage = $this->where(['article_id'=>$article_id])->find();
        return $manage->toArray();
    }

    /**
     * 修改
     */
    public function upd($article_id,$data)
    {
        $article = $this->findArt($article_id);
        if ($data['state'] == 2 ) {
            $data['release_time'] = 0;
        } else {
            if ($article['release_time'] == 0) {
                $data['release_time'] = time();
            }
        }
        $data['last_time'] = time();
        $result = $this->save($data,['article_id' => $article_id]);
        return $result;
    }
}
